<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>c2earn facebook app</title>
		<script type="text/javascript" src="json2.js"></script>
		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    </head>
    <body>
        <div id="fb-root"></div>
        <script type="text/javascript">
            window.fbAsyncInit = function() {
                FB.init({appId: '176984042359203', 
						status: true, 
						cookie: true, 
						xfbml: true, 
						oauth : true //enables OAuth 2.0
						});
 
                /* All the events registered */
				/*
                FB.Event.subscribe('auth.login', function(response) {
                    // do something with response
                    //login(response.authResponse.accessToken);
					showMe(response);
                });
				
                FB.Event.subscribe('auth.logout', function(response) {
                    // do something with response
                    //logout();
                });
				*/
                FB.getLoginStatus(function(response) {
                    if (response.authResponse) {
                        // logged in and connected user, someone you know
                        document.getElementById('accessstatus').innerHTML = 'in accessToken:' + response.authResponse.accessToken + '<br />status:' + response.status;
						//login(response.authResponse.accessToken);
						showMe(response);
						//call a ajax
						//callAjax(response);
                    } else {
						//FB.login();
						var url = getLoginUrl();
						top.location.href = url;
						document.getElementById('accessstatus').innerHTML = 'out response session' + '<br />status:' + response.status + '<br />' + url;
						//showMe(response);
					}
                });

            };
            (function() {
                var e = document.createElement('script');
                e.type = 'text/javascript';
                e.src = document.location.protocol +
                    '//connect.facebook.net/en_US/all.js';
                e.async = true;
                document.getElementById('fb-root').appendChild(e);
            }());
			
			function getLoginUrl(){
				var appid = '176984042359203';
				var appurl = encodeURI('http://apps.facebook.com/xm_apps/');
				var url = "https://graph.facebook.com/oauth/authorize?client_id="+appid+
						"&redirect_uri="+appurl+
						"&type=web_server&scope=user_about_me,user_birthday,user_hometown,user_location,email,read_stream";
				return url;
			}
			
			function callAjax(response){
				
					jQuery.ajax({
						  url: "../apps/index.php/index/saveUserInfo",
						  //global: false,
						  type: "POST",
						  data: {response : JSON.stringify(response)},
						  dataType: "json",
						  beforeSend: function(x) {
							if (x && x.overrideMimeType) {
							  x.overrideMimeType("application/j-son;charset=UTF-8");
							}
						  },
						  success: function(msg){
							//alert(msg.status);
							
							if( msg.status == 'exists' || msg.status == 'success' ) {
								window.location.href = "apps/index.php";
							}
							
							//var obj = JSON.parse(msg);
							//alert(obj.status);
						  }
					   }
					);
				
			}
/*
			FB.login(function(response) {
			   if (response.authResponse) {
				 console.log('Welcome!  Fetching your information.... ');
				 FB.api('/me', function(response) {
				   console.log('Good to see you, ' + response.name + '.');
				   FB.logout(function(response) {
					 console.log('Logged out.');
				   });
				 });
			   } else {
				 console.log('User cancelled login or did not fully authorize.');
			   }
			 }, {scope: 'email'});
*/
 /*
			function login(accessToken){
                FB.api('/me', function(response) {
                    document.getElementById('login').style.display = "block";
                    document.getElementById('login').innerHTML = response.name + " succsessfully logged in!" + accessToken;
                });
            }
            function logout(){
                document.getElementById('login').style.display = "none";
            }
	*/	
			function showMe(response){
				FB.api('/me', function(response) {
					var div = document.getElementById('me');
					var html = '<table>';
						/*
						html += (
						'<tr>' +
							'<th>status</th>' +
							'<td>' + response.status + '</td>' +	
						'</tr>' 
						);
						*/
					for (var key in response ) {
					  html += (

						'<tr>' +
						  '<th>' + key + '</th>' +
						  '<td>' + response[key] + '</td>' +
						'</tr>'
					  );
					}
					div.innerHTML = html;	
					//调用ajax，把用户数据写进数据库
					callAjax(response);
				});

			}

        </script>
 
        <h3>New Graph api & Javascript Base FBConnect Tutorial | Thinkdiff.net</h3>

        <br /><br /><br />
        <div id="login" style ="display:none"></div>
        <div id="name"></div>
		<div id="accessstatus"></div>
		<div id="me"></div>
		<div id="msg"></div>
 
    </body>
</html>

<?php
exit;
ini_set('display_errors', 1);

/**
	处理facebook用户登录授权
	如果facebook用户已经授权，跳转至 /Apps/  进入广告观看页面
	如果用户拒绝授权，则跳转至deny页面
*/

//if user denied
//	http://YOUR_CANVAS_PAGE?error_reason=user_denied&
//		error=access_denied&error_description=The+user+denied+your+request.
if (isset($_GET['error_reason']) && !empty($_GET['error_reason'])) {
	echo $_GET['error_description'];
	exit;
}

session_start();

//APP 请求的用户授权信息
$scope = array(
			//'offline_access',	//long time access
			'user_about_me,',	//
			'user_birthday,',
			'user_hometown,',
			'user_location,',
			'email,',
			'read_stream',		
);
$app_id = "176984042359203";  //facebook App ID
$secret = 'b78d67f25161d242fc972092b428ef99';	//facebook App Secret
$canvas_page = "http://apps.facebook.com/xm_apps/";		//facebook APP 主页

$auth_url = "https://www.facebook.com/dialog/oauth?client_id=" . $app_id . 
			"&redirect_uri=" . urlencode($canvas_page) .
			"&scope=";

//重新生成URL
foreach($scope as $v) {
	$auth_url .= $v;
}

$signed_request = $_REQUEST["signed_request"]; 

$data = parse_signed_request($signed_request, $secret);

     if (empty($data["user_id"])) {
			$_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
			$auth_url .= "&state=". $_SESSION['state'];
            echo("<script> top.location.href='" . $auth_url . "'</script>");
     } else {
			//获得用户授权Access Token
			//With this code in hand, you can proceed to the next step, app authentication, 
			//to gain the access token you need to make API calls.
			if(!empty($_REQUEST["code"])){
				$accessToken = getAccessToken($app_id, $canvas_page, $secret, $_REQUEST["code"] );
			}
			echo $accessToken;die;
			$userInfo = getUserInfo($accessToken);

			$_SESSION['facebook_user_info'] = $userInfo;
			$_SESSION['facebook_info'] = $data;
            header("Location:apps/");

			//echo ("Welcome User: " . $data["user_id"]);
			//echo '<br />';
			//print_r($data);
     } 

function parse_signed_request($signed_request, $secret) {
  list($encoded_sig, $payload) = explode('.', $signed_request, 2); 

  // decode the data
  $sig = base64_url_decode($encoded_sig);
  $data = json_decode(base64_url_decode($payload), true);

  if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
		error_log('Unknown algorithm. Expected HMAC-SHA256');
		return null;
  }

  // check sig
  $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
  if ($sig !== $expected_sig) {
    error_log('Bad Signed JSON signature!');
    return null;
  }

  return $data;
}

function base64_url_decode($input) {
  return base64_decode(strtr($input, '-_', '+/'));
}

/**
	get a access token key
*/
function getAccessToken($app_id, $my_url, $app_secret, $code){

	if($_REQUEST['state'] == $_SESSION['state']) {
		$token_url = "https://graph.facebook.com/oauth/access_token?"
					. "client_id=" . $app_id . "&redirect_uri=" . urlencode($my_url)
					. "&client_secret=" . $app_secret . "&code=" . $code;
					echo $token_url;die;
		$response = file_get_contents($token_url);
		echo $response;die;
		$params = null;
		parse_str($response, $params);
		echo $params['access_token'];die;
		return $params['access_token'];
	} else {
		return null;
	}
}

function getUserInfo($access_token){
    $graph_url = "https://graph.facebook.com/me?access_token=" 
				. $access_token;

    $user = json_decode(@file_get_contents($graph_url));
    return $user;
	
}



?>